package route

import (
	"encoding/json"
	// "fmt"
	"net/http"
	"strings"
)

// type RouteBase struct {
// 	path        string
// 	handle      http.Handler
// 	requestType string
// 	middleware  http.Handler
// }

// var R RouteBase
//路由map
var Route map[string]map[string]interface{} = make(map[string]map[string]interface{})

/**
*
*
**/
func Get(path string, handle func(http.ResponseWriter, *http.Request), middleware func(http.ResponseWriter, *http.Request, func(http.ResponseWriter, *http.Request))) {
	Route[path+"GET"] = map[string]interface{}{
		"path":       path,
		"handle":     handle,
		"type":       "GET",
		"middleware": middleware,
	}
	http.HandleFunc(path, index)
}
func Post(path string, handle func(http.ResponseWriter, *http.Request), middleware func(http.ResponseWriter, *http.Request, func(http.ResponseWriter, *http.Request))) {
	Route[path+"POST"] = map[string]interface{}{
		"path":       path,
		"handle":     handle,
		"type":       "POST",
		"middleware": middleware,
	}
	http.HandleFunc(path, index)
}
func Any(path string, handle func(http.ResponseWriter, *http.Request), middleware func(http.ResponseWriter, *http.Request, func(http.ResponseWriter, *http.Request))) {
	Route[path+"ANY"] = map[string]interface{}{
		"path":       path,
		"handle":     handle,
		"type":       "ANY",
		"middleware": middleware,
	}
	http.HandleFunc(path, index)
}

//统一入口
func index(w http.ResponseWriter, r *http.Request) {
	value, check := CheckRoute(r)
	if !check {
		bytes, _ := json.Marshal(map[string]interface{}{
			"code": 500,
			"msg":  "route not found",
		})
		w.Write(bytes)
		return
	}
	handler, _ := value["handle"].(func(http.ResponseWriter, *http.Request))
	ware, _ := value["middleware"].(func(http.ResponseWriter, *http.Request, func(http.ResponseWriter, *http.Request)))
	if handler != nil {
		if ware == nil {
			Middle(w, r, handler)
		} else {
			ware(w, r, handler)
		}

	}

}

//检测路由是否存在
func CheckRoute(r *http.Request) (map[string]interface{}, bool) {
	//处理路径
	path := r.RequestURI
	pathBytes := []rune(path)
	strIndex := strings.Index(path, "?")
	if strIndex != -1 {
		path = string(pathBytes[:strIndex])
	}
	value, exists := Route[path+r.Method]
	if !exists {
		return nil, false
	}
	return value, true
}
